import * as React from 'react'
import { Toast, Modal } from 'antd-mobile'
import { Button, Gird, Item, Radio, NavBar, Icon, FlatList, InputNumber, /* Image */ } from 'components'
// import { End } from '../../viewComponent'
import './index.less'
import { post, NotCart } from '../../utils'

const alert = Modal.alert

export default class Cart extends React.Component<any, any> {

    public state = {
        shops: [],
        editStatus: false,
        selectAll: false,
        allNumber: 0,
        allList: 0
    }

    public render(): JSX.Element {
        const { editStatus, selectAll } = this.state
        const { cartData } = this.props
        return (
            <div className="shop_cart">
                <NavBar
                    fixed={true}
                    className="shop_cart_nav divider"
                    title="购物车"
                    right={<div className="shop_cart_nav__right"><span className="label" onClick={this.handleEdit}>{editStatus ? '完成' : '编辑'}</span> <Icon type="msg" className="icon" /></div>}
                />

                <FlatList
                    data={cartData}
                    ListEmptyComponent={NotCart}
                    renderItem={(item: any, index: number) => {
                        return (
                            <Gird style={{ marginTop: 0, padding: 0 }} key={index}>
                                <React.Fragment>
                                    <Item className="shop_cart_title" title={<div><Radio checked={item.active} onChange={this.handleTitle.bind(this, index)} className="shop_cart_title_radio" /><Icon className="shop_cart_title_icon" type="shop" />{item.seller_name}</div>} />
                                    <FlatList
                                        data={item.goodslist}
                                        renderItem={(data, i: number) => {
                                            return (
                                                <div className="shop_cart_item flex" key={i}>
                                                    <div className="radio flex_justify">
                                                        <Radio checked={data.active} onChange={this.handleListRadio.bind(this, index, i)} />
                                                    </div>
                                                    <div className="img">
                                                        <img src={data.pic} />
                                                    </div>
                                                    <div className="flex_1 info">
                                                        <div className="title">{data.title}</div>
                                                        <div className="label">{data.spec}</div>
                                                        <div className="number flex">
                                                            <div className="flex_1"><span className="DINPro">{data.goods_price ? `${data.goods_price}+` : ''}{data.goods_price_q}</span><span className="right">恒豆</span></div>
                                                            <InputNumber min={1} value={data.number} onChange={this.handleNumber.bind(this, index, i)} />
                                                        </div>
                                                    </div>
                                                </div>
                                            )
                                        }}
                                    />
                                </React.Fragment>
                            </Gird>
                        )
                    }}
                />
                {/* <div className="shop_cart_top flex_center">
                    <img src={require('../../assets/cart_top.png')} />
                </div>
                <div className="gird list_hh" style={{ padding: '0 0.35rem' }}>
                    <FlatList
                        className="gird_content flex"
                        style={{ flexFlow: 'wrap' }}
                        data={cartData}
                        renderItem={(item: any, index: number) => {
                            return (
                                <div className="live_item" key={index}>
                                    <div className="live_item_img">
                                        <Image src={item.goods_pic} />
                                    </div>
                                    <div className="live_item_content">
                                        <div className="live_item_content_title">{item.goods_name}</div>
                                        <div className="live_item_content_label">
                                            ¥ {item.goods_price}+{item.goods_price_q}
                                            <span>恒豆</span>
                                        </div>
                                    </div>
                                </div>
                            )
                        }}
                    />
                </div>
                <End /> */}
                <div className="shop_cart_bar flex_justify">
                    <div className="flex">
                        <Radio checked={selectAll} className={editStatus ? 'radio flex_1' : 'radio'} onChange={this.selectAll}>全选</Radio>
                        {this.getBottomNode()}
                    </div>
                </div>
            </div>
        )
    }

    public componentDidMount() {
        this.getData()
    }

    private getData() {
        const { userInfo, SET_DETAIL_CART } = this.props
        post('cartapi/cartList', { userId: userInfo.id }).then((data: any) => {
            data = data.map((item: any) => {
                item.active = false
                item.goodslist = item.goodslist.map((i: any) => {
                    i.active = false
                    return i
                })
                return item
            })
            SET_DETAIL_CART(data)
        })
    }

    private getBottomNode() {
        const { editStatus, allNumber, allList } = this.state
        if (!editStatus) {
            return (
                <React.Fragment>
                    <div className="flex_1 info">合计：<span className="number">{allNumber}</span><span className="label">恒豆</span></div>
                    <Button className="btn" disabled={allList ? false : true} onClick={this.handleToBalance}>去结算({allList})</Button>
                </React.Fragment>
            )
        } else {
            return (
                <React.Fragment>
                    <Button className="btn_c" onClick={this.handleMoveCollect}>移入收藏</Button>
                    <Button className="btn_c del" onClick={this.handleDel}>删除商品</Button>
                </React.Fragment>
            )
        }

    }

    private handleDel = () => {
        const { selectAll } = this.state
        const { cartData, userInfo, SET_DETAIL_CART } = this.props
        const list = this.getCountVal(cartData)
        if (!list.number) {
            return
        }
        const ids: any[] = []
        const value: any[] = []
        cartData.map((item: any) => {
            const val: any = []
            item.goodslist.map((i: any) => {
                if (i.active) {
                    ids.push(i.id)
                } else {
                    val.push(i)
                }
            })
            if (val.length) {
                item.goodslist = val
                value.push(item)
            }
        })
        const styles: React.CSSProperties = { fontSize: '0.8rem', height: '2.25rem', lineHeight: '2.25rem', color: '#333333' }
        const node = <div style={{ color: '#333333', fontSize: '0.8rem' }}>确认要删除这{list.number}种商品么?</div>
        alert(<Icon type="tips" className="icon_tips" />, node, [
            { text: '取消', style: styles },
            {
                text: '确定', onPress: () => {
                    post('cartapi/cartDel', {
                        userId: userInfo.id,
                        ids: ids.join(',')
                    }).then((data: any) => {
                        SET_DETAIL_CART(value)
                        this.setState({
                            selectAll: value.length ? selectAll : false
                        })
                    }).catch((data: any) => {
                        Toast.info(data.msg, 2)
                    })
                },
                style: { ...styles, background: '#f33f2e', color: '#fff' }
            }
        ])
    }

    private handleToBalance = () => {
        const { history, cartData } = this.props
        const ids: any[] = []
        cartData.map((item: any) => {
            item.goodslist.map((i: any) => {
                if (i.active) {
                    ids.push(i.id)
                }
            })
        })
        history.push(`/fillOrder?cartIds=${ids.join(',')}`)
    }

    private handleMoveCollect = () => {
        const { selectAll } = this.state
        const { cartData, SET_DETAIL_CART } = this.props
        const list = this.getCountVal(cartData)
        if (!list.number) {
            return
        }
        const ids: any[] = []
        const value: any[] = []
        cartData.map((item: any) => {
            const val: any = []
            item.goodslist.map((i: any) => {
                if (i.active) {
                    ids.push(`${i.goods_id}|${i.id}`)
                } else {
                    val.push(i)
                }
            })
            if (val.length) {
                item.goodslist = val
                value.push(item)
            }
        })
        const styles: React.CSSProperties = { fontSize: '0.8rem', height: '2.25rem', lineHeight: '2.25rem', color: '#333333' }
        const node = <div style={{ color: '#333333', fontSize: '0.8rem' }}>当前选中的{list.number}种商品收藏成功后，将从购物车删除，请您确认</div>
        alert(<Icon type="tips" className="icon_tips" />, node, [
            { text: '我再想想', style: styles },
            {
                text: '移入收藏', onPress: () => {
                    post('cartapi/cartCollectDel', {
                        ids: ids.join(',')
                    }).then(() => {
                        Toast.info('收藏成功,可在我的收藏中查看', 2)
                        SET_DETAIL_CART(value)
                        this.setState({
                            selectAll: value.length ? selectAll : false
                        })
                    }).catch((data: any) => {
                        Toast.info(data.msg, 2)
                    })
                },
                style: { ...styles, background: '#f33f2e', color: '#fff' }
            }
        ])
    }

    private handleEdit = () => {
        const { editStatus } = this.state
        if (editStatus) {
            console.log(111)
        }
        this.setState({
            editStatus: !editStatus
        })
    }

    private handleTitle(index: number, status: boolean) {
        const { cartData, SET_DETAIL_CART } = this.props
        const value: any = [...cartData]
        value[index].active = status
        const val: any = value[index].goodslist.map((item: any) => {
            item.active = status
            return item
        })
        value[index].child = val
        const data = this.getCountVal(value)
        SET_DETAIL_CART(cartData)
        this.setState({
            allNumber: `${data.price.toFixed(2)}+${data.arch}`,
            allList: data.number,
            selectAll: value.every((item: any) => item.active)
        })
    }

    private handleListRadio(index: number, i: number, status: boolean) {
        const { cartData, SET_DETAIL_CART } = this.props
        const value: any = [...cartData]
        value[index].goodslist[i].active = !value[index].goodslist[i].active
        value[index].active = value[index].goodslist.every((item: any) => item.active)
        const data = this.getCountVal(value)
        SET_DETAIL_CART(cartData)
        this.setState({
            allNumber: `${data.price.toFixed(2)}+${data.arch}`,
            allList: data.number,
            selectAll: cartData.every((item: any) => item.active)
        })
    }

    private handleNumber(index: number, i: number, val: number) {
        const { cartData, userInfo, SET_DETAIL_CART } = this.props
        const value: any = [...cartData]
        value[index].goodslist[i].number = val
        Toast.loading('', 0)
        post('cartapi/cartEdit', {
            userId: userInfo.id,
            editstr: `${value[index].goodslist[i].id}-${value[index].goodslist[i].goods_list_id}-${val}`
        }).then(() => {
            value[index].goodslist[i].active = true
            const data = this.getCountVal(value)
            value[index].active = value[index].goodslist.every((item: any) => item.active)
            const time = () => {
                Toast.hide()
                SET_DETAIL_CART(value)
                this.setState({
                    allNumber: `${data.price.toFixed(2)}+${data.arch}`,
                    allList: data.number,
                    selectAll: value.every((item: any) => item.active)
                })
            }
            setTimeout(time, 200)
        })

    }

    private getCountVal(value: any[] = []): { number: number, arch: number, price: number } {
        let price = 0
        let arch = 0
        let num = 0
        value.map((item: any) => {
            item.goodslist.map((list: any) => {
                if (list.active) {
                    num++
                    price += Number(list.goods_price) * list.number
                    arch += Number(list.goods_price_q) * list.number
                }
            })
        })
        return {
            number: num,
            arch,
            price
        }
    }

    private selectAll = (status: boolean) => {
        const { cartData, SET_DETAIL_CART } = this.props
        let num = 0
        let qian = 0
        let q = 0
        const val = cartData.map((item: any) => {
            item.active = status
            item.child = item.goodslist.map((i: any) => {
                i.active = status
                if (item.active) {
                    num++
                    qian += Number(i.goods_price) * i.number
                    q += Number(i.goods_price_q) * i.number
                }
                return item
            })
            return item
        })
        SET_DETAIL_CART(val)
        this.setState({
            allNumber: `${qian.toFixed(2)}+${q}`,
            allList: num,
            selectAll: status
        })
    }
}